package br.urca.interceptor;

import javax.inject.Inject;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.Accepts;
import br.com.caelum.vraptor.AroundCall;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.controller.ControllerMethod;
import br.com.caelum.vraptor.interceptor.SimpleInterceptorStack;
import br.com.caelum.vraptor.validator.Severity;
import br.com.caelum.vraptor.validator.SimpleMessage;
import br.com.caelum.vraptor.validator.Validator;
import br.urca.controller.LoginController;
import br.urca.util.ValidacaoDados;

@Intercepts
public class LoginInterceptor {
	
	private String metodo;
	
	private ServletContext context;
	private HttpServletRequest request;
	private Validator validator;
	
	@Deprecated public LoginInterceptor() { }
	
	@Inject
	public LoginInterceptor(HttpServletRequest request,
			ServletContext context,
			Validator validator) {
		super();
		this.request = request;
		this.context = context;
		this.validator = validator;
	}
	
	@Accepts
	public boolean accepts(ControllerMethod method) {
		setMetodo(method.getMethod().getName());
		return method.getController().getType().equals(LoginController.class);
	}
	
	@AroundCall
	public void valida(SimpleInterceptorStack stack) {
		if (getMetodo().trim().equalsIgnoreCase("login")) {

			String login = request.getParameter("login");
			String senha = request.getParameter("senha");
			
			validator.addIf((login == null) || (senha == null)
					|| (login.equalsIgnoreCase(""))
					|| (senha.equalsIgnoreCase("")), new SimpleMessage(
					"Erro",
					"Campo de usuário ou senha não preenchido!",
					Severity.ERROR));

			validator.addIf(!ValidacaoDados.loginValido(login)
					|| !ValidacaoDados.senhaValida(senha), new SimpleMessage(
					"Erro", "Matrícula ou senha com caracteres inválidos!",
					Severity.ERROR));
		}
		stack.next();

	}

	public String getMetodo() {
		return metodo;
	}

	public void setMetodo(String metodo) {
		this.metodo = metodo;
	}

}
